/* eslint-disable react/jsx-handler-names */
import { Form, Switch, message, Rate } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';

import AssetIndexC from './assetIndex';
import dictData from './config';
import myStyle from './index.less';
import RelatedRulesC from './relatedRules';
import TradeDirectionC from './tradeDirection';

import { TabC, FormGroup, SecondHeaderC, DATA_ENTRY, PrimaryC, PrimaryGhostC } from '../../../components';

const FormItem = Form.Item;

function checkAll(item) {
  return item.checked == false;
}
function mapEnum(arr) {
  const temp = [];
  if (!arr) return temp;
  arr.map((item) => {
    temp.push({
      title: item.value,
      value: item.code,
    });
  });
  return temp;
}
class AddRuleC extends PureComponent {
  state = {
    isAllSelect: false, // 账户组是否全选
    admin: undefined, // 是否是管理员
    productData: [], // 产品下拉
    activeKey: '1', // 标签页 默认资产指标
    directionObj: {}, // 存储交易方向
    majorRuleIds: [], // 存储管理规则
    assetIndexObj: undefined, // 存储资产指标
    showMonitoringCycle: false, // 展示监控窗口
  };

  formGroupRef1 = React.createRef(); // 风险说明

  formGroupRef2 = React.createRef(); // 基本信息

  formGroupRef3 = React.createRef(); // 账户信息

  formRef = React.createRef(); // 开关

  componentDidMount() {
    const {
      limitSetting: { productList = [] },
      detailData,
    } = this.props;
    // eslint-disable-next-line react/no-did-mount-set-state
    this.setState({ productData: _.cloneDeep(productList) });
    this.queryFactorByIndexClass();
    // 详情回填监控窗口
    if (detailData?.appliedProductScope) this.controlValueChange(detailData?.appliedProductScope, '', 'flag');
    if (detailData?.expireTime) {
      // 详情时处理表单是否disabled
      this.settingField('expireTime', detailData?.expireTime ? moment(detailData?.expireTime) : undefined);
      this.settingField('effectiveTime', detailData?.effectiveTime ? moment(detailData?.effectiveTime) : undefined);
      this.settingField('ruleState', detailData.ruleState);
    } else {
      // 默认值处理表单是否disabled
      this.settingField('ruleState', true);
      this.settingField('expireTime', moment('2099-12-31'));
      this.settingField('effectiveTime', moment());
    }
  }

  componentWillUnmount() {
    // 离开前清空缓存数据
    this.props.dispatch({
      type: 'limitSetting/save',
      payload: {
        Factor: [],
      },
    });
  }

  // 查询计算因子
  queryFactorByIndexClass = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'limitSetting/queryFactorByIndexClass',
      payload: {},
    }).then((data) => {
      this.props.dispatch({
        type: 'limitSetting/save',
        payload: {
          Factor: data || [],
        },
      });
    });
  };

  // 点击确定
  submit = () => {
    this.saveTabData('submit'); // 保存tab数据
  };

  // 格式化提交参数 几个子组件的数据 在这里合并 提交给后端
  formatSubmitData = async () => {
    const { detailData, dispatch } = this.props;
    const { directionObj, majorRuleIds, assetIndexObj } = this.state;
    const res1 = await this.formGroupRef1.current.getFormGroupData(); // 风险说明
    const res2 = await this.formGroupRef2.current.getFormGroupData(); // 基本信息
    const res3 = await this.formGroupRef3.current.getFormGroupData(); // 账户信息
    const res4 = await this.formRef.current.validateFields(); // 底部启用switch按钮

    const fieldsValue = { ...res1, ...res2, ...res3, ...res4 };

    console.log(fieldsValue, '********', assetIndexObj, res4);
    if (!fieldsValue.priority) {
      message.warning('优先级必选');
      return;
    }
    if (!assetIndexObj) return; // 资产指标有值才可以新增
    let switchValues = {};
    if (JSON.stringify(directionObj) === '{}') {
      const tempArr = detailData && detailData.switchList ? detailData.switchList : dictData.switchList; // 考虑到用户未点击设置，交易方向设置初始化入参
      switchValues = this.getTradedirect(tempArr);
    } else {
      switchValues = directionObj;
    }
    console.log('交易方向', switchValues);
    // 考虑到用户未点击设置，关联规则初始化入参
    const majorRuleIdsValues = !majorRuleIds.length ? (detailData && detailData.majorRuleIds) || [] : majorRuleIds;
    console.log('关联规则', majorRuleIdsValues);
    console.log('资产指标', assetIndexObj);
    let appliedProductScope = typeof fieldsValue.appliedProductScope === 'string' ? fieldsValue.appliedProductScope.split(' ') : fieldsValue.appliedProductScope; // 当控制类别为字符串时转换成数组，因后端该字段设置为数组
    const arr = appliedProductScope.filter((item) => item === 'ALL');
    if (arr && arr.length) appliedProductScope = ['ALL'];
    let createObj = {};
    if (this.props.type == 2) {
      createObj = {
        // 后端编辑的时候 需要前端传参
        createPerson: detailData.createPerson,
        createTime: detailData.createTime,
        createTimeString: detailData.createTimeString,
        ruleNo: detailData.ruleNo,
      };
    }
    const params = {
      ...createObj,
      ...fieldsValue,
      ...switchValues,
      ...assetIndexObj,
      majorRuleIds: majorRuleIdsValues,
      effectiveTime: fieldsValue.effectiveTime.format('YYYY-MM-DD'),
      expireTime: fieldsValue.expireTime.format('YYYY-MM-DD'),
      ruleState: fieldsValue.ruleState == true ? 1 : 2,
      onlyForUnited: fieldsValue.onlyForUnited == true ? 1 : 2,
      pecentView: assetIndexObj.pecentView == '1',
      appliedProductScope,
      riskCategory: Number(fieldsValue.riskCategory),
      ruleApplyObj: Number(fieldsValue.ruleApplyObj),
      accountLevel: Number(fieldsValue.accountLevel),
      ordinance: fieldsValue.ordinance, // 监管法规 string
      riskLevel: Number(fieldsValue.riskLevel), // 风险等级 int
    };
    // eslint-disable-next-line promise/no-promise-in-callback
    dispatch({
      type: this.props.type == 2 && !detailData?.type ? 'limitSetting/modifyRule' : 'limitSetting/createRule',
      payload: {
        ...params,
        ruleId: this.props.type == 2 ? (detailData?.type ? undefined : detailData?.ruleId) : undefined, // 编辑的时候有id
      },
    }).then((res) => {
      if (res && res.success) {
        message.success(this.props.type == 2 && !detailData?.type ? '编辑限额信息成功' : '新增限额信息成功');
        this.props.onOk();
      } else {
        const msg = this.props.type == 2 && !detailData?.type ? '编辑限额信息失败' : '新增限额信息失败';
        message.error(res ? res.message || msg : msg);
      }
    });
  };

  // 获取交易方向入参格式
  getTradedirect = (switchList) => {
    console.log(switchList);
    const switchValues = {};
    switchList.map((item) => {
      switchValues[item.value] = item.checked;
    });
    switchValues.transactionDirectionControl = !switchList.some(checkAll);
    return switchValues;
  };

  // tab切换
  tabChange = (e) => {
    this.saveTabData(); // 保存tab数据
    this.setState({ activeKey: e });
  };

  saveTabData = (type) => {
    if (this.state.activeKey === '2') {
      // 保存交易方向 修改内容
      const directionObj = this.state.TradeDirection && this.state.TradeDirection.submit();
      this.setState(
        {
          directionObj,
        },
        () => {
          if (type == 'submit') {
            // 提交获取的数据有延迟 所以等state渲染完
            this.formatSubmitData();
          }
        },
      );
    } else if (this.state.activeKey === '3') {
      // 保存关联规则 修改内容
      const arr = this.state.relatedRef && this.state.relatedRef.state.choosedData;
      this.setState(
        {
          majorRuleIds: arr, // 关联规则
        },
        () => {
          if (type == 'submit') {
            // 提交获取的数据有延迟 所以等state渲染完
            this.formatSubmitData();
          }
        },
      );
    } else {
      // 资产指标
      this.state.AssetIndex &&
        this.state.AssetIndex.submit().then((obj) => {
          this.setState(
            {
              assetIndexObj: obj,
            },
            () => {
              if (type === 'submit') {
                // 提交获取的数据有延迟 所以等state渲染完
                this.formatSubmitData();
              }
            },
          );
        });
    }
  };

  /*
    产品组件
    列表结构，默认插入第一条数据“全选当前存续产品和新增产品”（替代“全部”）
    支持多选（选了第一条数据，后面的就不给选了）
    下拉数据中不包含到期产品
  */
  // 产品变更
  controlValueChange = (val, self, flag) => {
    console.log(val);
    const str = val.join(',');
    this.setState({
      showMonitoringCycle: str.indexOf('ALL') > -1 ? false : str.indexOf('DKCP') > -1,
    });

    if (flag) return; // 回填时监控窗口调用
    const { productData } = this.state;
    const arr = val && val.filter((item) => item === 'ALL');
    if (arr && arr.length) {
      productData.map((item) => {
        if (item.value !== 'ALL') item.disabled = true;
      });
      this.setState({
        productData: [...productData],
      });
      return val.filter((item) => item === 'ALL');
    }
    productData.map((item) => {
      if (item.value !== 'ALL') item.disabled = false;
    });
    this.setState({
      productData: [...productData],
    });
    return val;
  };

  // 启用状态
  ruleStateChange = (e) => {
    this.settingField('ruleState', e);
    if (!e) {
      // 启用状态关闭 仅作联合条件关闭
      this.formRef.current.setFieldsValue({
        onlyForUnited: false,
      });
    }
  };

  // 赋值表单值
  settingField = (field, val) => {
    this.setState({
      [field]: val,
    });
  };

  render() {
    const {
      detailData = {},
      limitSetting: { dictMap = {} },
      loading,
      globalM: { headerHeight },
    } = this.props;
    const { getFieldValue = () => {} } = this.formGroupRef2.current?.formRef?.current || {};
    const { getFieldsValue = () => {} } = this.formRef?.current || {};
    const { productData, activeKey, showMonitoringCycle } = this.state;
    return (
      <div className={myStyle.addRule}>
        <div style={{ height: headerHeight ? 'calc(100vh - 280px)' : 'calc(100vh - 214px)', overflowY: 'auto' }}>
          <FormGroup
            dataSource={[
              {
                dataIndex: 'ruleDesc',
                title: '风险说明',
                type: DATA_ENTRY.INPUT,
                initialValue: (detailData?.type ? '' : detailData.ruleDesc) || '',
                rules: [{ required: true, message: '请填写风险说明' }],
                lineOne: true,
              },
            ]}
            onRef={(ref) => {
              this.formGroupRef1.current = ref;
            }}
          />
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title='基本信息' />
          </div>
          <FormGroup
            dataSource={[
              {
                dataIndex: 'ruleApplyObj',
                title: '作用范围',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.ruleApplyObj ? detailData.ruleApplyObj.toString() : '1',
                rules: [{ required: true, message: '请选择作用范围' }],
                dataSource: dictData.applyObj,
              },
              {
                dataIndex: 'priority',
                title: '优先级',
                type: DATA_ENTRY.FORMOTHERC,
                initialValue: detailData.priority || 5,
                rules: [{ required: true, message: '请选择优先级' }],
                Children: <Rate count={9} className={myStyle.myStar} />,
              },
              {
                dataIndex: 'riskCategory',
                title: '风险类型',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.riskCategory ? `${detailData.riskCategory}` : undefined,
                rules: [{ required: true, message: '请选择风险类型' }],
                dataSource: dictMap.riskCategory ? mapEnum(dictMap.riskCategory) : [],
              },
              {
                dataIndex: 'riskLevel',
                title: '风险等级',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.riskLevel,
                rules: [{ required: true, message: '请选择风险等级' }],
                dataSource: dictMap.riskLevel ? mapEnum(dictMap.riskLevel) : [],
              },
              {
                dataIndex: 'ordinance',
                title: '监管法规',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.ordinance,
                dataSource: dictMap.riskOrdinance ? mapEnum(dictMap.riskOrdinance) : [],
              },
              {
                dataIndex: 'effectiveTime',
                title: '生效日期',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: detailData.effectiveTime ? moment(detailData.effectiveTime) : moment(),
                rules: [{ required: true, message: '请填写生效日期' }],
                allowClear: true,
                onChange: (e) => {
                  console.log(e, detailData);
                  this.settingField('effectiveTime', e || undefined);
                },
                disableBegin: moment().subtract(1, 'days'),
                disableEnd: this.state.expireTime,
              },
              {
                dataIndex: 'expireTime',
                title: '失效日期',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: detailData.expireTime ? moment(detailData.expireTime) : moment('2099-12-31'),
                rules: [{ required: true, message: '请填写失效日期' }],
                allowClear: true,
                disableBegin: this.state.effectiveTime,
                onChange: (e) => {
                  this.settingField('expireTime', e || undefined);
                },
              },
            ]}
            onRef={(ref) => {
              this.formGroupRef2.current = ref;
            }}
          />

          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title='账户信息' />
          </div>
          <FormGroup
            onRef={(ref) => {
              this.formGroupRef3.current = ref;
            }}
            dataSource={[
              {
                dataIndex: 'accountLevel',
                title: '账户层次',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.accountLevel || '2',
                rules: [{ required: true, message: '请选择账户层次' }],
                dataSource: dictData.accountLevel,
              },
              {
                dataIndex: 'appliedProductScope',
                title: '产品',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.appliedProductScope,
                rules: [{ required: true, message: '请选择产品' }],
                dataSource: productData,
                filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
                showSearch: true,
                isMultiple: true,
                allowClear: true,
                getValueFromEvent: this.controlValueChange,
              },
              {
                dataIndex: 'monitoringCycle',
                title: '监控窗口',
                type: DATA_ENTRY.INPUTNUMBER,
                initialValue: detailData.monitoringCycle,
                hide: !showMonitoringCycle,
                unit: '日',
                helper: '开放前X个工作日及开放日当日',
                precision: 0,
                min: 1,
              },
              {
                dataIndex: 'productControlType',
                title: '账户控制',
                type: DATA_ENTRY.SELECT,
                initialValue: detailData.productControlType,
                dataSource: dictData.productControlType,
                rules: [{ required: true, message: '请选择账户控制' }],
              },
            ]}
          />
          <TabC
            tabSource={[
              {
                title: '资产指标',
                key: '1',
                content: <AssetIndexC detailData={detailData} changeDetailData={this.props.changeDetailData} onRef={(ref) => this.setState({ AssetIndex: ref })} />,
              },
              {
                title: '交易方向',
                key: '2',
                content: <TradeDirectionC dataList={detailData.switchList || dictData.switchList} onRef={(ref) => this.setState({ TradeDirection: ref })} />,
              },
              {
                title: '关联规则',
                key: '3',
                content: (
                  <RelatedRulesC
                    modalType={this.props.type}
                    choosedData={detailData.majorRuleIds || []}
                    ruleId={detailData.ruleId}
                    tenant={localStorage.getItem('antd-pro-tenant')}
                    onRef={(ref) => this.setState({ relatedRef: ref })}
                  />
                ),
              },
            ]}
            onChange={this.tabChange}
            activeKey={activeKey}
          />

          <Form ref={this.formRef}>
            <div className={myStyle.ruleStatus}>
              <FormItem colon={false} label='启用' valuePropName='checked' name='ruleState' initialValue={detailData.ruleState ? detailData.ruleState == 1 : true}>
                <Switch onChange={this.ruleStateChange} checkedChildren='开' unCheckedChildren='关' />
              </FormItem>
              <FormItem
                colon={false}
                label='仅作联合条件'
                valuePropName='checked'
                name='onlyForUnited'
                initialValue={detailData.onlyForUnited ? detailData.onlyForUnited == 1 : false}
              >
                <Switch checkedChildren='开' unCheckedChildren='关' disabled={!this.state.ruleState} />
              </FormItem>
            </div>
          </Form>
        </div>

        <div className={myStyle.saveBtn}>
          <PrimaryGhostC title='取消' onClick={() => this.props.onCancle()} style={{ marginRight: '16px' }} />
          <PrimaryC title='确定' loading={loading.effects['limitSetting/createRule'] === true || loading.effects['limitSetting/modifyRule'] === true} onClick={this.submit} />
        </div>
      </div>
    );
  }
}
export default connect(({ limitSetting, dictionaryM, userM: user, loading, globalM }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
  globalM,
}))(AddRuleC);
